<?php

namespace wxpay;
/*
 * 联速lspay
 */
use think\Log;
class lspay
{
    protected $appid;
    protected $mch_id;
    protected $key;
    protected $openid;
    public function __construct($openid, $mch_id, $key, $app_id, $name, $ooid, $price,$notifyurl)
    {
        $this->openid = $openid;
        $this->mch_id = $mch_id;
        $this->key = $key;
        $this->app_id = $app_id;
        $this->name = $name;
        $this->ooid = $ooid;
        $this->price = $price;
        $this->notifyurl = $notifyurl;
    }
    public function pay()
    {
        //统一下单接口
        $return = $this->weixinapp();
        return $return;
    }
    //统一下单接口
    private function unifiedorder()
    {
        $url = 'https://api.lspay.tech/gateway/unifiedorder';
        $parameters = array(
            'mch_no' => $this->mch_id, //商户号
            'app_id' => $this->app_id, //应用ID
            'mch_order_no' => $this->ooid, //商户生成的订单号
            'way_code' => 'WX_LITE_JUMP', //支付方式,如微信小程序WX_LITE
            'amount' => floatval($this->price * 100), //支付金额,单位分
            'currency' => 'cny', //三位货币代码,人民币
            'subject' => $this->name, //商品标题
            'body' => $this->name, //商品描述
            'notify_url' => $this->notifyurl, //通知地址
            'req_time' => $this->getTime13(), //请求接口时间,13位时间戳
            'version' => '1.0', //接口版本号，固定：1.0
//            'sign' => '', //签名值，详见签名算法
            'sign_type' => 'MD5', //	签名类型，目前只支持MD5方式
            'channel_extra' => json_encode(['openid' => $this->openid])
        );
        //统一下单签名
        $parameters['sign'] = $this->getSign($parameters);
        $xmlData = http_build_query($parameters, '', '&');
        $return = $this->postXmlCurl($xmlData, $url, 60);
        return json_decode($return,true);
    }
    //获取13位时间戳
    protected function getTime13(){
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    private static function postXmlCurl($reqdata, $url, $second = 30)
    {
        // halt($reqdata);
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
        //设置header
//        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $reqdata);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 40);
        set_time_limit(0);
        log::write(["msg"=>"联速请求参数","data"=>$reqdata],"log");
// halt($reqdata);
        //运行curl
        $data = curl_exec($ch);
        // halt($data);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            echo ("curl出错，错误码:$error");
        }
    }

    //微信小程序接口
    private function weixinapp()
    {
        //统一下单接口
        $unifiedorder = $this->unifiedorder();
        
      
        
        $res = $unifiedorder['data']['pay_info'];
        
        $res['reqsn']=$unifiedorder['data']['mch_order_no'];
        $res['pay_order_id']=$unifiedorder['data']['pay_order_id'];
        $res['sfzfid']=1;
       
       
       /* $parameters = array(
            'appId' => $res['appId'], //小程序ID
            'timeStamp' => $res['timeStamp'], //时间戳
            'nonceStr' => $res['nonceStr'], //随机串
            'package' => $res['package'], //数据包
            'signType' => $res['signType'], //签名方式
            'paySign' => $res['paySign'] //签名
        );*/
        return $res;
    }
    //作用：生成签名
    private function getSign($Obj)
    {
        ksort($Obj);
        $rows = [];
        foreach ($Obj as $key => $value) {
            if (! $value || $key == 'sign') {
                continue;
            }
            $rows[] = "{$key}={$value}";
        }
        $string = implode('&', $rows);
        $strSign = $string.'&key='.$this->key;
        return strtoupper(MD5($strSign));
    }
    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}
